package project_model;

import java.util.ArrayList;
import java.util.List;

public class VisitorTest {

    private interface Visitor {
        void visit(Element element);
    }

    private static class Visitor1 implements Visitor {
        @Override
        public void visit(Element element) {
            System.out.println("访问者1访问" + element.show());
        }
    }

    private static class Visitor2 implements Visitor {
        @Override
        public void visit(Element element) {
            System.out.println("访问者2访问" + element.show());
        }
    }

    private interface Element {
        void accept(Visitor visitor);

        String show();
    }

    private static class Element1 implements Element {
        @Override
        public void accept(Visitor visitor) {
            visitor.visit(this);
        }

        @Override
        public String show() {
            return "元素操作A";
        }
    }

    private static class Element2 implements Element {
        @Override
        public void accept(Visitor visitor) {
            visitor.visit(this);
        }

        @Override
        public String show() {
            return "元素操作B";
        }
    }

    private static class VisitorOperator {
        private List<Element> elementList = new ArrayList<>();

        public void accept(Visitor visitor) {
            for(Element element : elementList) {
                element.accept(visitor);
            }
        }

        private void add(Element element) {
            elementList.add(element);
        }

        private void remove(Element element) {
            elementList.remove(element);
        }
    }

    public static void main(String[] args) {
        VisitorOperator visitorOperator = new VisitorOperator();
        visitorOperator.add(new Element1());
        visitorOperator.add(new Element2());
        visitorOperator.accept(new Visitor1());
        visitorOperator.accept(new Visitor2());
    }
}
